﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Xml;
using DispatchAssist.Service;
using System.Web.Services.Protocols;

namespace DispatchAssist.AppHost
{
    [ModuleContract("0faea184-c355-4bbe-a36d-c0c664bf733d", "系统管理", "角色管理")]
    public partial class RoleManage : MdiUserControl
    { 
        AuthService authService = new AuthService();
        List<SeatRole> roles = new List<SeatRole>();
        List<SeatUser> validUsers = new List<SeatUser>();
        public RoleManage()
            : base()
        {
            InitializeComponent();
        }

        public RoleManage(XmlNode node)
            : this()
        {
        }
        public override void Onload()
        {
            base.Onload();
            authService.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();
            BindRoleList();
            pnlRoleList.Visible = true;
            grpEditRole.Visible = false;
            this.btnDelete.Enabled = true;
            this.btnCreate.Enabled = true;
            this.btnEdit.Enabled = true;
        }


        private void BindRoleList()
        {
            try
            {
                SeatRole[] arrRoles = authService.GetAllSeatRole();
                if (arrRoles != null)
                {
                    roles = arrRoles.ToList<SeatRole>();
                    List<SystemModule> modules = authService.GetSystemModules().ToList<SystemModule>();
                    foreach (SeatRole role in roles)
                    {
                        int powerFlag = role.PowerFlag;
                        role.Powers = GetPowers(powerFlag, modules);
                    }
                    dgvdRoleList.AutoGenerateColumns = false;
                    if (roles != null)
                    {
                        dgvdRoleList.DataSource = roles;
                    }
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private string GetPowers(int powerFlag, List<SystemModule> modules)
        {
            StringBuilder powers = new StringBuilder();
            foreach (SystemModule module in modules)
            {
                if ((powerFlag & module.ModuleFlag) != 0)
                {
                    powers.Append(module.ModuleName);
                    powers.Append(",");
                }
            }
            string strPower = powers.ToString();
            if (strPower.Contains(","))
            {
                strPower = strPower.Substring(0, strPower.Length - 1);
            }
            return strPower;
        }

        private void btnCreateEdit_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Tag.ToString() == "create")
            {
                CreateRole();
            }
            else if ((sender as Button).Tag.ToString() == "edit")
            {
                EditRole();
            }
        }

        private void EditRole()
        {
            if (dgvdRoleList.SelectedRows == null || dgvdRoleList.SelectedRows.Count <= 0 || dgvdRoleList.SelectedRows.Count > 1)
            {
                MessageBox.Show("请选择要编辑的记录行！");
                return;
            }
            rowID = this.dgvdRoleList.CurrentRow.Index;
            Guid roleID = new Guid(System.Convert.ToString(dgvdRoleList.CurrentRow.Cells["RoleID"].Value));
            txtRoleName.Text = System.Convert.ToString(dgvdRoleList.CurrentRow.Cells["RoleName"].Value);
            int powerFlag = System.Convert.ToInt32(dgvdRoleList.CurrentRow.Cells["PowerFlag"].Value);
            this.btnSave.Tag = System.Convert.ToString(roleID);
            BindModules();
            BindUserModules(powerFlag);
            pnlRoleList.Visible = true;
            grpEditRole.Visible = true;
            this.btnCreate.Enabled = false;
            this.btnEdit.Enabled = false;
            this.btnDelete.Enabled = false;
        }

        private void BindUserModules(int powerFlag)
        {
            //chklistPermission.
            for (int i = 0; i < this.chklistPermission.Items.Count; i++)
            {
                int moduleFlag = ((SystemModule)(chklistPermission.Items[i])).ModuleFlag;
                if ((powerFlag & moduleFlag) != 0)
                {
                    chklistPermission.SetItemChecked(i, true);//设置选中
                }
                else
                {
                    chklistPermission.SetItemChecked(i, false);
                }
            }
        }

        private void CreateRole()
        {
            BindModules();
            for (int i = 0; i <= chklistPermission.Items.Count - 1; i++)
            {
                chklistPermission.SetItemChecked(i, false);
            }
            rowID = this.dgvdRoleList.CurrentRow.Index;
            btnSave.Tag = "create";
            txtRoleName.Text = string.Empty;
            pnlRoleList.Visible = true;
            grpEditRole.Visible = true;
            this.btnCreate.Enabled = false;
            this.btnEdit.Enabled = false;
            this.btnDelete.Enabled = false;
        }

        private void BindModules()
        {
            try
            {
                SystemModule[] arrModules = authService.GetSystemModules();
                if (arrModules != null)
                {
                    List<SystemModule> modules = arrModules.ToList<SystemModule>();
                    this.chklistPermission.DataSource = modules;
                    this.chklistPermission.DisplayMember = "ModuleName";
                    this.chklistPermission.ValueMember = "ModuleFlag";
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SeatRole sr = roles.Find(s => s.RoleName == txtRoleName.Text);

            string tag = System.Convert.ToString((sender as Button).Tag);
            if (string.IsNullOrEmpty(txtRoleName.Text))
            {
                MessageBox.Show("请输入角色名称！");
                return;
            }
            if (chklistPermission.CheckedItems.Count <= 0)
            {
                MessageBox.Show("请选择权限！");
                return;
            }
            if (tag == "create")
            {
                if (sr != null)
                {
                    MessageBox.Show("角色名称已经存在！");
                    return;
                }


                SaveNewRole();
            }
            else if (!string.IsNullOrEmpty(tag))
            {
                if (sr.RoleName != txtRoleName.Text && sr != null)
                {
                    MessageBox.Show("角色名称已经存在！");
                    return;
                }
                SaveEditRole(tag);
            }

            pnlRoleList.Visible = true;
            grpEditRole.Visible = false;
        }

        private void SaveEditRole(string roleID)
        {
            int powerFlag = 0;
            for (int i = 0; i <= chklistPermission.Items.Count - 1; i++)
            {
                if (chklistPermission.GetItemChecked(i))
                {
                    int moduleFlag = ((SystemModule)(chklistPermission.Items[i])).ModuleFlag;
                    powerFlag = powerFlag | moduleFlag;
                }
            }
            SeatRole role = new SeatRole();
            role.RoleID = new Guid(roleID);
            role.RoleName = txtRoleName.Text;
            role.PowerFlag = powerFlag;
            try
            {
                if (authService.UpdateSeatRole(role))
                {
                    MessageBox.Show("保存成功！");
                    BindRoleList();
                    this.btnCreate.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnDelete.Enabled = true;
                }
                else
                {
                    MessageBox.Show("保存失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void SaveNewRole()
        {
            int powerFlag = 0;
            for (int i = 0; i <= chklistPermission.Items.Count - 1; i++)
            {
                if (chklistPermission.GetItemChecked(i))
                {
                    int moduleFlag = ((SystemModule)(chklistPermission.Items[i])).ModuleFlag;
                    powerFlag = powerFlag | moduleFlag;
                }
            }
            SeatRole role = new SeatRole();
            role.RoleName = txtRoleName.Text;
            role.PowerFlag = powerFlag;
            try
            {
                if (authService.CreateSeatRole(role))
                {
                    MessageBox.Show("添加成功！");
                    BindRoleList();
                    this.btnCreate.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnDelete.Enabled = true;
                }
                else
                {
                    MessageBox.Show("添加失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            pnlRoleList.Visible = true;
            grpEditRole.Visible = false;
            this.btnCreate.Enabled = true;
            this.btnEdit.Enabled = true;
            this.btnDelete.Enabled = true;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvdRoleList.SelectedRows == null || dgvdRoleList.SelectedRows.Count <= 0 || dgvdRoleList.SelectedRows.Count > 1)
            {
                MessageBox.Show("请选择要删除的记录行！");
                return;
            }
            if (MessageBox.Show("确认删除此角色？", "删除确认", MessageBoxButtons.OKCancel) != DialogResult.OK)
            {
                return;
            }


            Guid roleID = new Guid(System.Convert.ToString(dgvdRoleList.CurrentRow.Cells["RoleID"].Value));

            validUsers = authService.GetAllSeatUser(1).ToList<SeatUser>();
            SeatUser su = null;
            if (validUsers != null && validUsers.Count > 0)
            {
                su = validUsers.Find(s => s.RoleID == roleID);
            }
            if (su != null)
            {
                if (DialogResult.Cancel == MessageBox.Show("有用户正在使用该角色，确定删除该角色吗?", "提示", MessageBoxButtons.OKCancel))
                return;
            }



            try
            {
                if (authService.DeleteSeatRole(roleID))
                {
                    MessageBox.Show("删除成功！");
                    BindRoleList();
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }
        int rowID = -1;

        private void dgvdRoleList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((rowID != -1) && this.grpEditRole.Visible && (dgvdRoleList.CurrentRow.Index != rowID))
            {
                if (MessageBox.Show("是否撤销当前编辑？", "编辑确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    dgvdRoleList.Rows[rowID].Selected = true;
                }
                else
                {
                    grpEditRole.Visible = false;
                    this.btnCreate.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnDelete.Enabled = true;
                }
            }
        }
    }
}
